<!-- 新增用户 -->
<template>
  <Modal
    class="add_form"
    v-model="modal"
    :title="`${userId ? '编辑' : '新增'}用户`"
    :mask-closable="false"
    draggable
    sticky
    scrollable
    @on-cance="cancel"
    @on-visible-change="cancel"
    width="800px"
  >
    <Form
      ref="formEl"
      :model="formData"
      :rules="rules"
      :label-width="140"
      :key="formKeys"
    >
      <div class="flex_form_item">
        <FormItem
          label="用户名"
          prop="username"
        >
          <Input
            v-model="formData.username"
            placeholder="请输入用户名"
            clearable
          ></Input>
        </FormItem>
      </div>
      <div class="flex_form_item flex-form">
        <FormItem label="姓名" prop="uname">
          <Input
            v-model="formData.uname"
            placeholder="请输入姓名"
            clearable
          ></Input>
          <Input
            v-model="formData.lastname"
            placeholder="中文名"
            clearable
          ></Input>
        </FormItem>
      </div>
      <div class="flex_form_item">
        <FormItem label="电子邮件" prop="email">
          <Input
            v-model="formData.email"
            placeholder="请输入电子邮件"
            clearable
          ></Input>
        </FormItem>
      </div>

      <div class="flex_form_item flex-form">
        <FormItem label="密码" prop="password">
          <Input
            type="password"
            v-model="formData.password"
            placeholder="请输入密码"
            clearable
            password
          ></Input>
          <Input
            type="password"
            v-model="formData.repassword"
            placeholder="请再次输入密码"
            clearable
            password
          ></Input>
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="密码强度">
          <password-power :password="formData.password"/>
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="手机号">
          <Input
            v-model="formData.mobile"
            placeholder="请输入手机号"
            clearable
          ></Input>
        </FormItem>
      </div>
      <div class="flex_form_item">
        <FormItem label="管理员" prop="usertype">
          <Switch
            v-model="formData.usertype"
            :true-value="0"
            :false-value="1"
          >
            <template #open>
              <span>是</span>
            </template>
            <template #close>
              <span>否</span>
            </template>
          </Switch>
        </FormItem>
      </div>
      <div class="flex_form_item">
        <FormItem label="离线坐席">
          <Switch
            size="large"
            v-model="formData.gdpr"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>

          <Switch
            class="long-switch"
            v-model="formData.disableautologin"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>禁用登录软电话</span>
            </template>
            <template #close>
              <span>自动登录软电话</span>
            </template>
          </Switch>
        </FormItem>
      </div>
      <div class="flex_form_item">
        <FormItem label="质检坐席">
          <Switch
            v-model="formData.qcagent"
            size="large"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>
        </FormItem>
      </div>
      <div class="flex_form_item">
        <FormItem label="呼叫中心坐席" prop="callcenter">
          <Switch
            v-model="formData.callcenter"
            size="large"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>开启</span>
            </template>
            <template #close>
              <span>关闭</span>
            </template>
          </Switch>

          <Switch
            v-model="formData.bindext"
            class="long-switch"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>禁用分机绑定</span>
            </template>
            <template #close>
              <span>启用分机绑定</span>
            </template>
          </Switch>
        </FormItem>
      </div>

      <template v-if="+formData.bindext">
        <div class="flex_form_item flex-form">
          <FormItem label="语音服务器">
            <Select
              v-model="formData.hostid"
              clearable
              transfer
              filterable
              placeholder="请选择语音服务器"
              @on-change="hostChange"
            >
              <Option
                v-for="item in hostList"
                :value="item.id"
                :key="item.id"
              >{{ item.hostname }}</Option>
            </Select>

            <Select
              v-model="formData.extid"
              transfer
              filterable
              placeholder="请选择分机"
            >
              <Option
                v-for="item in extList"
                :value="item.id"
                :key="item.id"
              >{{ `${item.extention} ${item.username ? `(${item.username})` : '' }` }}</Option>
            </Select>
          </FormItem>
        </div>

        <div class="flex_form_item">
          <FormItem label="启用多分机绑定">
            <Switch
              v-model="formData.enablemultext"
              size="large"
              :true-value="1"
              :false-value="0"
            >
              <template #open>
                <span>开启</span>
              </template>
              <template #close>
                <span>关闭</span>
              </template>
            </Switch>
          </FormItem>
        </div>

        <template v-if="+formData.enablemultext">
          <div class="flex_form_item">
            <FormItem label="SIP分机">
              <Select
                v-model="formData.sipextention"
                clearable
                transfer
                filterable
                placeholder="请选择SIP分机"
              >
                <Option
                  v-for="item in extList"
                  :value="item.id"
                  :key="item.id"
                >{{ `${item.extention} ${item.username ? `(${item.username})` : '' }` }}</Option>
              </Select>
            </FormItem>

            <FormItem
              label="WebRTC分机"
              :label-width="100"
            >
              <Select
                v-model="formData.webrtcextention"
                clearable
                transfer
                filterable
                placeholder="请选择WebRTC分机"
              >
                <Option
                  v-for="item in extList"
                  :value="item.id"
                  :key="item.id"
                >{{ `${item.extention} ${item.username ? `(${item.username})` : '' }` }}</Option>
              </Select>
            </FormItem>
          </div>
        </template>
      </template>

      <template v-if="+formData.callcenter">
        <div class="flex_form_item">
          <FormItem label="野外模式">
            <Switch
              v-model="formData.enableoutside"
              :true-value="1"
              :false-value="0"
            >
              <template #open>
                <span>是</span>
              </template>
              <template #close>
                <span>否</span>
              </template>
            </Switch>
          </FormItem>
        </div>

        <div class="flex_form_item">
          <FormItem label="呼叫权限">
            <Switch
              v-model="formData.enablecallaccess"
              size="large"
              :true-value="1"
              :false-value="0"
            >
              <template #open>
                <span>开启</span>
              </template>
              <template #close>
                <span>关闭</span>
              </template>
            </Switch>
          </FormItem>
        </div>
      </template>

      <div class="flex_form_item">
        <FormItem label="启用自动结束后处理" >
          <Switch v-model="formData.enableautoendafter" :true-value="1"
          :false-value="0">
            <template #open>
              <span>是</span>
            </template>
            <template #close>
              <span>否</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem
          v-if="+formData.enableautoendafter"
          label="后处理时长(秒)"
          label-width="110"
        >
          <InputNumber
            :min="0"
            v-model="formData.autoendaftertime"
          />
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="多媒体坐席">
          <Switch
            v-model="formData.agent"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>是</span>
            </template>
            <template #close>
              <span>否</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem
          v-if="+formData.agent"
          label="最大接入访客"
          label-width="110"
        >
          <Select
            v-model="formData.maxuser"
            transfer
            placeholder="请选择最大接入访客"
          >
            <Option
              v-for="(value, key) in MAX_VISTOR_OPTIONS"
              :value="+key"
              :key="key"
            >{{ value }}</Option>
          </Select>
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="邮件坐席">
          <Switch
            v-model="formData.mailagent"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>是</span>
            </template>
            <template #close>
              <span>否</span>
            </template>
          </Switch>
        </FormItem>

        <FormItem
          v-if="+formData.mailagent"
          label="最大分配邮件"
          label-width="110"
        >
          <Select
            v-model="formData.maxmail"
            transfer
            placeholder="请选择最大分配邮件"
          >
            <Option :value="0">默认</Option>
            <Option
              v-for="item in MAX_MAIL_OPTIONS"
              :value="item"
              :key="item"
            >{{ item }}</Option>
          </Select>
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="最大客户数量">
          <InputNumber
            :min="0"
            v-model="formData.ecmax"
          />
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="语言">
          <Select
            v-model="formData.language"
            transfer
            placeholder="请选择语言"
          >
            <Option
              v-for="(value,key) in LANG_OPTIONS"
              :value="key"
              :key="key"
            >{{ value }}</Option>
          </Select>
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="权限密码">
          <Input
            type="password"
            v-model="formData.permissionspwd"
            placeholder="请输入权限密码"
            clearable
            password
          ></Input>
        </FormItem>
      </div>

      <div class="flex_form_item">
        <FormItem label="账号类型">
          <Select
            v-model="formData.department"
            clearable
            transfer
            placeholder="请选择账号类型"
          >
            <Option
              v-for="(value,key) in USER_TYPE_OPTIONS"
              :value="key"
              :key="key"
            >{{ value }}</Option>
          </Select>
        </FormItem>
      </div>

      <template v-if="userId">
        <div class="flex_form_item">
          <FormItem label="报表管理员">
            <Switch
              v-model="formData.reportadmin"
              :true-value="1"
              :false-value="0"
            >
              <template #open>
                <span>开</span>
              </template>
              <template #close>
                <span>关</span>
              </template>
            </Switch>
          </FormItem>
        </div>
      
        <div class="flex_form_item">
          <FormItem label="报表可查看无部门">
            <Switch
              v-model="formData.reportnoorgan"
              :true-value="1"
              :false-value="0"
            >
              <template #open>
                <span>开</span>
              </template>
              <template #close>
                <span>关</span>
              </template>
            </Switch>
          </FormItem>
        </div>
      </template>

      <div class="flex_form_item">
        <FormItem label="启用坐席辅助">
          <Switch
            v-model="formData.asr"
            :true-value="1"
            :false-value="0"
          >
            <template #open>
              <span>开</span>
            </template>
            <template #close>
              <span>关</span>
            </template>
          </Switch>
        </FormItem>
      </div>
    </Form>

    <template #footer>
      <Button @click="cancel">取消</Button>
      <Button
        type="primary"
        @click="submit"
      >立即提交</Button>
    </template>
  </Modal>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Message } from 'view-ui-plus'
import {
  userCreate,
  userUpdate,
  userDetail,
  extentionList,
  pbxhostMylist
} from '@/api/modules/department'
import PasswordPower from '@/components/FormComponents/PasswordPower.vue'

const LANG_OPTIONS = {
  zh_CN: '中文简体',
  ph_PH: '菲律宾语',
  zh_TC: '中文繁体',
  en_US: 'English'
}

const USER_TYPE_OPTIONS = {
  '00': '个险',
  '10': '团险'
}

const MAX_VISTOR_OPTIONS = {
  0: '默认',
  1: 1,
  2: 2,
  3: 3,
  4: 4,
  5: 5,
  10: 10,
  15: 15,
  20: 20,
  30: 30
}

const MAX_MAIL_OPTIONS = Array.from(
  new Array(10),
  (item, index) => +`${index + 1}0`
)
const formKeys = ref(0)
const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const modal = ref(true)

// 加载
const loading = ref(true)

// 表单元素ref
const formEl = ref(null)

// 表单字段
const formData = ref({
  username: '',
  uname: '',
  lastname: '',
  email: '',
  password: '',
  repassword: '',
  mobile: '',
  usertype: 1, //管理员
  gdpr: 0, //离线坐席
  disableautologin: 0, //软登录电话
  qcagent: 0, //质检坐席
  callcenter: 0, //呼叫中心坐席
  bindext: 0, //分机绑定
  agent: 0, //多媒体坐席
  mailagent: 0, //邮件坐席
  ecmax: 0,
  language: 'zh_CN',
  department: '', //账号类型
  permissionspwd: '', //权限密码
  asr: 0, //坐席辅助
  reportadmin: 0, //报表管理员
  reportnoorgan: 0, //报表可查看无部门
  enableautoendafter: 0,

  enableoutside: 0, //野外模式
  enablecallaccess: 0, //呼叫权限
  enablemultext: 0, //启用多分机绑定
  hostid: '', //语言服务
  extid: '', //分机,
  sipextention: '', //SIP分机
  webrtcextention: '', //WebRTC分机
  autoendaftertime: 0, //后处理时长
  maxuser: 0, //最大接入访客
  maxmail: 0 //最大分配邮件
})

const userId = ref(undefined)
// 表单校验条件
const rules = ref({
  username: [{ required: true, message: '请填写用户名称', trigger: 'blur' }],
  uname: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
  email: [
    { required: false, message: '请正确输入电子邮件', trigger: 'blur', validator: (row, val, callback) => {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/
      if(emailRegex.test(val) || !val) {
        return callback()
      }
      callback(new Error())
    } }
  ],
  // usertype: [{ required: false, message: '请选择是否管理员', trigger: 'change' }],
  // callcenter: [{ required: false, message: '请选择是否呼叫中心坐席', trigger: 'change' }],
  // agent: [{ required: false, message: '请选择是否多媒体坐席', trigger: 'change' }],
  // maxuser: [{ required: false, message: '请填写最大接入访客', trigger: 'change' }],
  // callcenter: [{ required: true, message: '请选择是否呼叫中心坐席', trigger: 'change' }],
  // callcenter: [{ required: true, message: '请选择是否呼叫中心坐席', trigger: 'change' }],
  // departmentId: [
  //   { required: true, message: '请选择所属部门', trigger: 'change' }
  // ],
  // roleId: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  password: [
    { required: true, message: '请填写密码', trigger: 'blur' },
    { required: true, message: '密码必须包含字母和数字,且长度大于6', trigger: 'blur', validator: (row, val, callback) => {
      const passwordRegex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/
      if(passwordRegex.test(val) || (userId.value && !val)) {
        return callback()
      }
      callback(new Error())
    }},
    { required: true, message: '密码不得大于16位', trigger: 'blur', validator: (row, val, callback) => {
      if((val && val.length < 16) || (userId.value && !val)) {
        return callback()
      }
      callback(new Error())
    } }
  ]
})

//获取语音服务列表
const hostList = ref([])
const getPbxhostMylist = () => {
  pbxhostMylist().then(({ data }) => {
    hostList.value = data
  })
}

//获取分机列表
const extList = ref([])
const getExtentionList = () => {
  if (!formData.value.hostid) {
    return (extList.value = [])
  }

  extentionList({
    data: {
      hostid: formData.value.hostid
    }
  }).then(({ data }) => {
    extList.value = data.extentionPage.content
  })
}

const hostChange = () => {
  Object.assign(formData.value, {
    extid: '',
    sipextention: '',
    webrtcextention: ''
  })
  getExtentionList()
}

const getUserDetail = () => {
  userDetail({
    data: {
      id: userId.value
    }
  }).then(({data})=>{
    const unEditKeys = ['password', 'repassword']

    for(const key in formData.value) {
      if(unEditKeys.includes(key)) {
        continue
      }

      if(typeof data[key] === 'boolean' || ['0', '1'].includes(data[key])) {
        formData.value[key] = +data[key]
        continue
      }
      formData.value[key] = data[key]
    }
    console.log(formData.value)

    getExtentionList()
  })
}

const passwordValidate = () => {
  const { password, repassword } = formData.value

  if(userId.value && !password && !repassword) {
    return true
  }

  if(!repassword || password !== repassword) {
    Message.warning('两次输入的密码不一致，请确认')
    return
  }

  return true
}
/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  if(!passwordValidate()) return

  loading.value = true

  try {
    await ( userId.value ? userUpdate : userCreate)({
      data: {
        ...formData.value,
        id: userId.value
      }
    })

    Message.success('操作成功')

    emit('submit')
    
  } catch (error) {
    console.log(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  emit('cancel')
}

const initDialog = (id) => {
  if(!id) return
  userId.value = id

  rules.value.password[0].required = false
  formKeys.value++
  getUserDetail()
}

defineExpose({
  initDialog
})

onMounted(() => {
  getPbxhostMylist()
})
</script>

<style scoped lang="scss">
.flex-form {
  :deep(.ivu-form-item-content) {
    display: flex;
    .ivu-input-wrapper:first-child {
      margin-right: 20px;
    }
    .ivu-select:first-child {
      margin-right: 20px;
    }
  }
}
.long-switch {
  width: 120px;
  margin-left: 120px;
  &.ivu-switch-checked::after {
    left: 99px;
  }
}
.ivu-input-wrapper,
.ivu-select {
  width: 240px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>